<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆人脸识别入馆系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            margin: 0;
            padding: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            font-family: 'Microsoft YaHei', sans-serif;
            overflow: auto;
            min-height: 100vh;
        }
        
        .fullscreen-container {
            position: relative;
            width: 100%;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .header {
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 20px;
            text-align: center;
            backdrop-filter: blur(10px);
        }
        
        .main-content {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .recognition-panel {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
            text-align: center;
            max-width: 600px;
            width: 100%;
            backdrop-filter: blur(10px);
        }
        
        .camera-container {
            position: relative;
            margin: 30px 0;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        }
        
        #video {
            width: 100%;
            height: 400px;
            object-fit: cover;
            background: #000;
        }
        
        .camera-overlay {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 200px;
            height: 200px;
            border: 3px solid #28a745;
            border-radius: 50%;
            box-shadow: 0 0 20px rgba(40, 167, 69, 0.5);
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { box-shadow: 0 0 20px rgba(40, 167, 69, 0.5); }
            50% { box-shadow: 0 0 30px rgba(40, 167, 69, 0.8); }
            100% { box-shadow: 0 0 20px rgba(40, 167, 69, 0.5); }
        }
        
        .control-buttons {
            margin-top: 30px;
        }
        
        .btn-capture {
            background: linear-gradient(45deg, #28a745, #20c997);
            border: none;
            color: white;
            padding: 15px 40px;
            font-size: 18px;
            border-radius: 50px;
            margin: 0 10px;
            transition: all 0.3s ease;
            box-shadow: 0 5px 15px rgba(40, 167, 69, 0.3);
        }
        
        .btn-capture:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(40, 167, 69, 0.4);
        }
        
        .btn-exit {
            background: linear-gradient(45deg, #dc3545, #c82333);
            border: none;
            color: white;
            padding: 15px 40px;
            font-size: 18px;
            border-radius: 50px;
            margin: 0 10px;
            transition: all 0.3s ease;
            box-shadow: 0 5px 15px rgba(220, 53, 69, 0.3);
        }
        
        .btn-exit:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(220, 53, 69, 0.4);
        }
        
        .status-display {
            margin-top: 20px;
            padding: 15px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: bold;
        }
        
        .status-waiting {
            background: rgba(255, 193, 7, 0.2);
            color: #856404;
            border: 2px solid #ffc107;
        }
        
        .status-processing {
            background: rgba(0, 123, 255, 0.2);
            color: #004085;
            border: 2px solid #007bff;
        }
        
        .status-success {
            background: rgba(40, 167, 69, 0.2);
            color: #155724;
            border: 2px solid #28a745;
        }
        
        .status-error {
            background: rgba(220, 53, 69, 0.2);
            color: #721c24;
            border: 2px solid #dc3545;
        }
        
        .loading-spinner {
            display: none;
            margin: 20px auto;
        }
        
        .seat-info {
            margin-top: 20px;
            padding: 20px;
            background: rgba(40, 167, 69, 0.1);
            border-radius: 10px;
            border: 2px solid #28a745;
        }
        
        .seat-number {
            font-size: 24px;
            font-weight: bold;
            color: #28a745;
        }
    </style>
</head>
<body>
    <div class="fullscreen-container">
        <div class="header">
            <h1><i class="fas fa-camera"></i> 图书馆人脸识别入馆系统</h1>
            <p>请将面部对准摄像头，系统将自动识别并分配座位</p>
            <div class="permission-notice" style="
                background: #fff3cd;
                border: 1px solid #ffeaa7;
                border-radius: 5px;
                padding: 15px;
                margin: 15px 0;
                font-size: 14px;
                color: #856404;
            ">
                <strong>📷 摄像头权限提示：</strong><br>
                首次使用时，浏览器会询问摄像头权限，请点击"允许"以正常使用人脸识别功能。
                如果不小心点击了"拒绝"，请点击地址栏左侧的摄像头图标重新设置权限。
            </div>
        </div>
        
        <div class="main-content">
            <div class="recognition-panel">
                <h3><i class="fas fa-user-check"></i> 人脸识别验证</h3>
                
                <div class="camera-container">
                    <video id="video" autoplay muted></video>
                    <div class="camera-overlay"></div>
                    <canvas id="canvas" style="display: none;"></canvas>
                </div>
                
                <div class="control-buttons">
                    <button id="captureBtn" class="btn btn-capture">
                        <i class="fas fa-camera"></i> 开始识别
                    </button>
                    <button id="exitBtn" class="btn btn-exit">
                        <i class="fas fa-times"></i> 退出系统
                    </button>
                </div>
                
                <div id="statusDisplay" class="status-display status-waiting">
                    <i class="fas fa-info-circle"></i> 请点击"开始识别"按钮进行人脸识别
                </div>
                
                <div class="loading-spinner">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">识别中...</span>
                    </div>
                </div>
                
                <div id="seatInfo" class="seat-info" style="display: none;">
                    <h4><i class="fas fa-chair"></i> 座位分配信息</h4>
                    <div class="seat-number" id="seatNumber"></div>
                    <p id="seatDetails"></p>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let video, canvas, context;
        let stream = null;
        
        // 初始化摄像头
        async function initCamera() {
            try {
                video = document.getElementById('video');
                canvas = document.getElementById('canvas');
                context = canvas.getContext('2d');
                
                // 检查浏览器是否支持摄像头
                if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                    throw new Error('浏览器不支持摄像头功能');
                }
                
                // 请求摄像头权限
                stream = await navigator.mediaDevices.getUserMedia({
                    video: {
                        width: { ideal: 640 },
                        height: { ideal: 480 },
                        facingMode: 'user'
                    }
                });
                
                video.srcObject = stream;
                updateStatus('waiting', '摄像头已就绪，请点击"开始识别"按钮');
            } catch (error) {
                console.error('摄像头初始化失败:', error);
                let errorMessage = '摄像头初始化失败';
                
                if (error.name === 'NotAllowedError') {
                    errorMessage = '摄像头权限被拒绝，请在浏览器地址栏左侧点击摄像头图标允许访问';
                } else if (error.name === 'NotFoundError') {
                    errorMessage = '未找到摄像头设备，请检查摄像头是否连接';
                } else if (error.name === 'NotReadableError') {
                    errorMessage = '摄像头被其他应用占用，请关闭其他使用摄像头的程序';
                } else {
                    errorMessage = `摄像头初始化失败: ${error.message}`;
                }
                
                updateStatus('error', errorMessage);
                showCameraPermissionHelp();
            }
        }
        
        // 更新状态显示
        function updateStatus(type, message) {
            const statusDisplay = document.getElementById('statusDisplay');
            statusDisplay.className = `status-display status-${type}`;
            
            const icons = {
                waiting: 'fas fa-info-circle',
                processing: 'fas fa-spinner fa-spin',
                success: 'fas fa-check-circle',
                error: 'fas fa-exclamation-triangle'
            };
            
            statusDisplay.innerHTML = `<i class="${icons[type]}"></i> ${message}`;
        }
        
        // 显示欢迎信息和座位信息
        function showWelcomeMessage(message, studentName, seatData) {
            const seatInfo = document.getElementById('seatInfo');
            const seatNumber = document.getElementById('seatNumber');
            const seatDetails = document.getElementById('seatDetails');
            
            seatNumber.innerHTML = `
                <div class="welcome-message">
                    <h2>${message || '欢迎进入图书馆！'}</h2>
                    <p class="student-name">学生：${studentName}</p>
                </div>
                <div class="seat-number">${seatData.seat_number}</div>
            `;
            seatDetails.innerHTML = `
                <strong>楼层:</strong> ${seatData.floor}楼<br>
                <strong>分配方式:</strong> ${seatData.assignment_type}<br>
                <strong>使用时间:</strong> ${new Date().toLocaleString()}
            `;
            
            seatInfo.style.display = 'block';
        }
        
        // 拍照并识别
        async function captureAndRecognize() {
            try {
                updateStatus('processing', '正在进行人脸识别，请保持面部正对摄像头...');
                document.querySelector('.loading-spinner').style.display = 'block';
                
                // 设置canvas尺寸
                canvas.width = video.videoWidth;
                canvas.height = video.videoHeight;
                
                // 绘制当前视频帧到canvas
                context.drawImage(video, 0, 0);
                
                // 获取图片数据
                const imageData = canvas.toDataURL('image/jpeg', 0.8);
                
                // 发送到后端进行识别
                const response = await fetch('/admin/face_recognition/library_entry', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: JSON.stringify({
                        image: imageData
                    })
                });
                
                const result = await response.json();
                document.querySelector('.loading-spinner').style.display = 'none';
                
                if (result.success) {
                    updateStatus('success', `识别成功！欢迎 ${result.student_name}`);
                    showWelcomeMessage(result.message, result.student_name, result.seat_info);
                    
                    // 5秒后自动重置
                    setTimeout(() => {
                        resetInterface();
                    }, 5000);
                } else {
                    updateStatus('error', result.message || '识别失败，请重试');
                    
                    // 3秒后重置状态
                    setTimeout(() => {
                        updateStatus('waiting', '请点击"开始识别"按钮进行人脸识别');
                    }, 3000);
                }
            } catch (error) {
                console.error('识别过程出错:', error);
                document.querySelector('.loading-spinner').style.display = 'none';
                updateStatus('error', '识别过程中发生错误，请重试');
                
                setTimeout(() => {
                    updateStatus('waiting', '请点击"开始识别"按钮进行人脸识别');
                }, 3000);
            }
        }
        
        // 显示摄像头权限帮助
        function showCameraPermissionHelp() {
            const helpDiv = document.createElement('div');
            helpDiv.id = 'cameraHelp';
            helpDiv.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: white;
                padding: 30px;
                border-radius: 10px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.3);
                z-index: 1000;
                max-width: 500px;
                text-align: center;
            `;
            
            helpDiv.innerHTML = `
                <h3 style="color: #e74c3c; margin-bottom: 20px;">摄像头权限设置</h3>
                <p style="margin-bottom: 15px;">请按以下步骤允许摄像头访问：</p>
                <ol style="text-align: left; margin-bottom: 20px;">
                    <li>点击浏览器地址栏左侧的摄像头图标</li>
                    <li>选择"始终允许"或"允许"</li>
                    <li>刷新页面重新尝试</li>
                </ol>
                <p style="font-size: 14px; color: #666; margin-bottom: 20px;">
                    如果仍然无法使用，请确保：<br>
                    • 摄像头设备已正确连接<br>
                    • 没有其他程序占用摄像头<br>
                    • 使用HTTPS或localhost访问
                </p>
                <button onclick="closeCameraHelp()" style="
                    background: #3498db;
                    color: white;
                    border: none;
                    padding: 10px 20px;
                    border-radius: 5px;
                    cursor: pointer;
                    margin-right: 10px;
                ">我知道了</button>
                <button onclick="location.reload()" style="
                    background: #27ae60;
                    color: white;
                    border: none;
                    padding: 10px 20px;
                    border-radius: 5px;
                    cursor: pointer;
                ">刷新页面</button>
            `;
            
            document.body.appendChild(helpDiv);
        }
        
        // 关闭摄像头权限帮助
        function closeCameraHelp() {
            const helpDiv = document.getElementById('cameraHelp');
            if (helpDiv) {
                helpDiv.remove();
            }
        }
        
        // 重置界面
        function resetInterface() {
            updateStatus('waiting', '请点击"开始识别"按钮进行人脸识别');
            document.getElementById('seatInfo').style.display = 'none';
        }
        
        // 退出系统
        function exitSystem() {
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
            }
            window.location.href = '/admin';
        }
        
        // 事件监听器
        document.getElementById('captureBtn').addEventListener('click', captureAndRecognize);
        document.getElementById('exitBtn').addEventListener('click', exitSystem);
        
        // 键盘快捷键
        document.addEventListener('keydown', function(event) {
            if (event.code === 'Space') {
                event.preventDefault();
                captureAndRecognize();
            } else if (event.code === 'Escape') {
                exitSystem();
            }
        });
        
        // 页面加载完成后初始化摄像头
        window.addEventListener('load', initCamera);
        
        // 页面卸载时释放摄像头
        window.addEventListener('beforeunload', function() {
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
            }
        });
    </script>
</body>
</html>